package com.imarad.server.util;

/**
 * @author hhu 【huan.hu@cnambition.com】
 * @version com.imarad.demo, v 0.1 2018/1/30 13:41 hhu Exp $$
 */
public class ServerUtils {
    /**
     * @param bytes
     * @param pos   byte转化起始位
     * @return
     */
    public static int bytesToInt(byte[] bytes, int pos) {
        return bytes[pos + 3] & 0xFF | (bytes[pos + 2] & 0xFF) << 8 | (bytes[pos + 1] & 0xFF) << 16
               | (bytes[pos] & 0xFF) << 24;
    }

    /**
     * @param a
     * @return
     */
    public static byte[] intToBytes(int a) {
        return new byte[] { (byte) ((a >> 24) & 0xFF), (byte) ((a >> 16) & 0xFF),
                            (byte) ((a >> 8) & 0xFF), (byte) (a & 0xFF) };
    }

    /**
     * @param bytes
     * @param pos   byte转化起始位
     * @return
     */
    public static long bytesToLong(byte[] bytes, int pos) {
        long l;
        l = bytes[pos];
        l &= 0xff;
        l |= ((long) bytes[pos + 1] << 8);
        l &= 0xffff;
        l |= ((long) bytes[pos + 2] << 16);
        l &= 0xffffff;
        l |= ((long) bytes[pos + 3] << 24);
        l &= 0xffffffffL;
        l |= ((long) bytes[pos + 4] << 32);
        l &= 0xffffffffffL;
        l |= ((long) bytes[pos + 5] << 40);
        l &= 0xffffffffffffL;
        l |= ((long) bytes[pos + 6] << 48);
        l &= 0xffffffffffffffL;
        l |= ((long) bytes[pos + 7] << 56);
        return (long) Double.longBitsToDouble(l);
    }

    /**
     * @param b
     * @param pos byte转化起始位
     * @return
     */
    public static short bytesToShort(byte[] b, int pos) {
        short s0 = (short) (b[pos] & 0xff);
        short s1 = (short) (b[pos + 1] & 0xff);
        s1 <<= 8;
        return (short) (s0 | s1);
    }
}